package com.magicode.portal.service.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.taglibs.standard.tag.common.core.ParamParent;
import org.hibernate.mapping.Array;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.magicode.cms.entiy.base.News;
import com.magicode.cms.entiy.base.OfflineEvents;
import com.magicode.cms.entiy.base.OfflineEventsEnterprise;
import com.magicode.cms.entiy.base.OfflineEventsUser;
import com.magicode.cms.entiy.base.User;
import com.magicode.common.dao.ICommonDaoService;
import com.magicode.common.dao.PageResults;
import com.magicode.portal.service.ISecOffLineService;


@Service("secOffLineService")
@Transactional
public class SecOffLineServiceImpl implements ISecOffLineService {
	
	@Autowired
	@Qualifier("commonDaoService")
	private ICommonDaoService commonDaoService;
	
	@Override
	public OfflineEvents get(String id) {
		String hql = " from com.magicode.cms.entiy.base.OfflineEvents o "
				+ " left join fetch o.source "
				+ " left join fetch o.author "
				+ " left join fetch o.mainPic "
				+ " left join fetch o.province "
				+ " left join fetch o.city "
				+ " left join fetch o.sponsorEnt "
				+ " left join fetch o.coSponsorEnt "
				+ " left join fetch o.eventSubject "
//				+ " left join fetch o.payType "
//				+ " left join fetch o.tags "
				+ " where o.id=? ";
		OfflineEvents events = null;
		try {
			events = (OfflineEvents) this.commonDaoService.getByHQL(hql, new String[]{id});
			{
				String coEntSql = "select t from "+OfflineEventsEnterprise.class.getName() +" t "
						+ " left outer join fetch t.enterprise  "
						+ " where "
						+ " t.coOfflineEvents.id = :id  ";
				Map map = new HashMap();
				map.put("id", id);
				List<OfflineEventsEnterprise> coEntList = this.commonDaoService.queryList(coEntSql, map);
				events.setCoSponsorEnts(coEntList);
				String entName = "";
				for(OfflineEventsEnterprise ent : coEntList){
					entName += ent.getEnterprise().getTitle()+",";
				}
	//			截取最后一位
				if(coEntList != null && coEntList.size() > 0){
					entName = entName.substring(0, entName.length() - 1);
				}
				events.setCoSponsorEntsName(entName);
			}
			{

				String coEntSql = "select t from  "+OfflineEventsEnterprise.class.getName() +" t "
						+ " left outer join fetch t.enterprise  "
						+ " where "
						+ " t.offlineEvents.id = :id  ";
				Map map = new HashMap();
				map.put("id", id);
				List<OfflineEventsEnterprise> entList = this.commonDaoService.queryList(coEntSql, map);
				events.setSponsorEnts(entList);
				String entName = "";
				for(OfflineEventsEnterprise ent : entList){
					entName += ent.getEnterprise().getTitle()+",";
				}
//				截取最后一位
				if(entList != null && entList.size() > 0){
					entName = entName.substring(0, entName.length() - 1);
				}
				events.setSponsorEntsName(entName);
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return events;
	}

	@Override
	public void update(OfflineEvents events) {
		try {
			this.commonDaoService.update(events);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void signup(String id, User user) throws Exception {
		OfflineEvents events = (OfflineEvents) this.commonDaoService.get(OfflineEvents.class, id);
		//增加报名人数
		Integer clickCount = events.getAttendUserCount();
		if(clickCount != null){
			clickCount++;
			events.setAttendUserCount(clickCount);
		}else{
			events.setAttendUserCount(1);
		}
		this.commonDaoService.merge(events);
		//持久化关联对象
		OfflineEventsUser eventsUser = new OfflineEventsUser();
		eventsUser.setOfflineEvents(events);
		eventsUser.setUser(user);
		eventsUser.setApplyTime(new Date());
		this.commonDaoService.save(eventsUser);
	}

	@Override
	public Integer getSignupCount(String eventId) throws Exception {
		String hql = " from com.magicode.cms.entiy.base.OfflineEventsUser o where o.offlineEvents.id=? ";
		List list = new ArrayList();
		try {
			list = this.commonDaoService.getListByHQL(hql, new String[]{eventId});
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list.size();
	}

	@Override
	public Boolean ifSignup(String eventId, User user) throws Exception {
		String hql = "select count(*) from com.magicode.cms.entiy.base.OfflineEventsUser o "
				+ " where o.user.id=? and o.offlineEvents.id=? ";
		List list = new ArrayList();
		try {
			String userid = "";
			if(user!=null){
				userid = user.getId();
			}
			list = this.commonDaoService.getListByHQL(hql, new String[]{userid,eventId});
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(list != null && list.size()>0){
			Long count = (Long) list.get(0);
			if(count > 0){
				return true;
			}
		}
		return false;
	}

	@Override
	public List<OfflineEvents> getInterested(String eventid) {
		String hql = " from com.magicode.cms.entiy.base.OfflineEvents o where 1=1 ";
		
		String[] param;
		if(eventid!=null){
			param = new String[1];
			param[0] = eventid;
			hql += "and o.id<>? ";
		}else{
			param = null;
		}
		hql += "order by  o.eventSubject.id desc ,o.city.id desc,o.endTime desc, o.createTime desc ";
		List<OfflineEvents> list = new ArrayList();
		try {
			PageResults results = this.commonDaoService.findPageByFetchedHql(hql, null, 1, 4, param);
			list = results.getResults();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<Map<String,Object>> getInterestedArticle(String articleid) {
		String sql = "select temp.* from (select t.news_id,count(t.tag_id) from news_tag_rela as t join news as n on t.news_id=n.id where t.tag_id " +
				" in (select b.tag_id from news_tag_rela as b where b.news_id ='"+articleid+"') and t.news_id<>'"+articleid+
				"' group by t.news_id order by n.subcribe_time desc,count(t.tag_id) desc) as temp limit 0,4";
		List<Object[]> list = commonDaoService.getListBySQL(sql);	
		String articleids = "";
		if(null!=list && list.size()>0){
			articleids = "";
			for(Object[] obj : list){
				String  newid =obj[0].toString();
				if(!newid.equals(articleid)){
					articleids+="'"+newid+"',";
				} 
			}
			articleids +="".equals(articleids)?"": articleids.substring(0, articleids.length()-1)+"";
		}
		if(!"".equals(articleids)){
			String gethql=" select new Map( "
					+ "t.id as id ,t.title as title ,t.shortTitle as shortTitle, "
					+ " t.subcribeTime as subcribeTime , "
					+ " source.title as sourceTitle, "
					+ " t.mainPic.minPath as imgul, "
					+ " t.commentsCount as commentsCount )"
					+ " from "+News.class.getName()+" t left join t.source as source where t.type=1 "
					+"  and t.status=2  and t.id in ("+articleids+")";
			List<Map<String,Object>> result = commonDaoService.queryList(gethql, 0, 4, null);
			if(result!=null && result.size()<4){
				String hql=" select new Map( "
						+ " t.id as id , t.title as title, "
						+ "t.shortTitle as shortTitle, "
						+ " t.subcribeTime as subcribeTime , "
						+ " source.title as sourceTitle, "
						+ " t.mainPic.minPath as imgul,"
						+ " t.commentsCount as commentsCount )"
						+ " from "+News.class.getName()+" t left join t.source as source where t.type=1 "
						+" and t.status=2 order by t.clickCount desc,t.subcribeTime desc ";
				List<Map<String,Object>> resulthql = commonDaoService.queryList(hql, 0, 4, null);
				if(resulthql!=null && resulthql.size()>0){
					for(int i=0;i<resulthql.size();i++){
						result.add(resulthql.get(i));
						if(result.size()==4){
							break;
						}
					}
				}
			}
			return result;
		}
		return null;
	}
	/**
	 * 获得参加人员
	 * @param eventid
	 * @return
	 * @throws Exception 
	 */
	@Override
	public List<User> getAttendUsers(String eventid) throws Exception {
		// TODO Auto-generated method stub
		String sql = " select distinct u from "+OfflineEventsUser.class.getName() +" t , "+User.class.getName()+" u "
				+ "  "
				+ "  left join fetch u.mainPic"
				+ " where u = t.user and  t.offlineEvents.id = :eventId "
				+ " order by t.applyTime asc ";
		Map paraMap = new HashMap();
		paraMap.put("eventId", eventid);
		List<User> list = commonDaoService.queryList(sql, paraMap);	
		
		return list;
	}
	/**
	 * 获得已参加人数
	 * @param eventid
	 * @return
	 * @throws Exception 
	 */
	@Override
	public Long getAttendUserCounts(String eventid) throws Exception {
		Long count = null;
		// attendCount已报人数
		String sql = " select sum(t.attendCount) from "+OfflineEventsUser.class.getName() +" t  "
				+ "  "
				+ " where t.offlineEvents.id = :eventId "
				+ " ";
		Map paraMap = new HashMap();
		paraMap.put("eventId", eventid);
		count = commonDaoService.countByHqlMap(sql, paraMap);	
		
		return count;
	}
}

